// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import { UINames } from "../Enums/UIEnum";
import BaseUI from "../UIs/BaseUI";
import DialogUI from "../UIs/UIs/DialogUI";
import TipsUI from "../UIs/UIs/TipsUI";

const { ccclass, property } = cc._decorator;

@ccclass
export default class UIManager extends cc.Component {

    @property([cc.Prefab])
    uiPrefabList: cc.Prefab[] = [];

    uiNodeList: Map<string, cc.Node> = new Map();


    private static _single: UIManager;
    public static get single(): UIManager {
        return UIManager._single;
    }

    protected onLoad(): void {
        if (UIManager._single == null) {
            UIManager._single = this;
        } else {
            this.node.destroy();
            this.node.removeFromParent();
        }

        cc.game.addPersistRootNode(this.node);

        this.initUIs();
    }

    initUIs() {
        for (const iterator of this.uiPrefabList) {
            var uinode = cc.instantiate(iterator);
            uinode.getComponent(BaseUI).uiname = iterator.name;
            this.uiNodeList.set(iterator.name, uinode);
        }
    }
    getUINode(uiname: string): cc.Node {
        return this.uiNodeList.get(uiname);
    }

    showUI(uiname: string) {
        var uinode = this.getUINode(uiname);
        if (uinode == null) {
            return;
        }
        if (uinode.parent != null) {
            uinode.removeFromParent();
        }
        var canvas = cc.find("Canvas");
        canvas.addChild(uinode);
    }
    closeUI(uiname: string) {
        var uinode = this.getUINode(uiname);
        if (uinode == null) {
            return;
        }
        uinode.removeFromParent();
    }
    showTips(str: string) {
        var uinode = this.getUINode(UINames.TipsUI);
        if (uinode == null) {
            return;
        }
        if (uinode.parent != null) {
            uinode.removeFromParent();
        }
        var canvas = cc.find("Canvas");
        canvas.addChild(uinode);
        var ui = uinode.getComponent(TipsUI);
        ui.label.string = str;
    }

    showDialog(desStr: string, sureFun: Function = null, cancelFun: Function = null, caller: any = null, isShowCancel: boolean = false) {
        var uinode = this.getUINode(UINames.DialogUI);
        if (uinode == null) {
            return;
        }
        if (uinode.parent != null) {
            uinode.removeFromParent();
        }
        var canvas = cc.find("Canvas");
        canvas.addChild(uinode);
        var ui = uinode.getComponent(DialogUI);
        ui.sureFun = sureFun;
        ui.cancelFun = cancelFun;
        ui.caller = caller;
        ui.cancelBtn.node.active = isShowCancel;
        ui.describeTxt.string = desStr;
    }

}
